
#include <stdlib.h>

#include "list.h"

void geopoint_list_init (geopoint_list_t *list)
{
	list->head = NULL;
	list->tail = NULL;
	list->size = 0;
}

static void
insert_after (geopoint_list_t *list, geopoint_list_node_t *node,
	geopoint_list_node_t *new_node)
{
	new_node->prev = node;
	new_node->next = node->next;
	
	if (node->next == NULL) {
		list->tail = new_node;
	} else {
		node->next->prev = new_node;
	}
	
	node->next = new_node;
}

static void
insert_before (geopoint_list_t *list, geopoint_list_node_t *node,
	geopoint_list_node_t *new_node)
{
	new_node->prev = node->prev;
	new_node->next = node;
	
	if (node->prev == NULL) {
		list->head = new_node;
	} else {
		node->prev->next = new_node;
	}
	
	node->prev = new_node;
}

static void
insert_beginning (geopoint_list_t *list, geopoint_list_node_t *new_node)
{
	if (list->head == NULL) {
		list->head = new_node;
		list->tail = new_node;
		new_node->prev = NULL;
		new_node->next = NULL;
	} else {
		insert_before (list, list->head, new_node);
	}
}

void geopoint_list_insert (geopoint_list_t *list, void *data)
{
	geopoint_list_node_t new_node;
    new_node.data = data;
	
	if (list->tail == NULL) {
		insert_beginning (list, &new_node);
	} else {
		insert_after (list, list->tail, &new_node);
	}
}
